package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${filePath}")
    private String filePath;

    @PostMapping("/upload")
    public R<String> upload(@RequestBody() MultipartFile file) throws IOException {
        /*//获取请求过来的图片
        String originalFilename = file.getOriginalFilename();
        //获取图片后缀名
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);

        //生成一个唯一的图片名
        String fileName = UUID.randomUUID()+suffix;

        File filePath1 = new File(filePath);
        //不存在则创建目录
        if (!filePath1.exists()) {
            filePath1.mkdirs();
        }
        //把图片上传到服务器的某个文件夹
        file.transferTo(new File(filePath+fileName));

        return R.success(fileName);*/

        //获取请求过来的图片名字
        String fileName = file.getOriginalFilename();
        //获取后缀名
        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);

        //生成唯一id
        String newFilePath = UUID.randomUUID() + suffix;

        //判断服务器路径是否存在，不存在则创建
        File ServiceFilePath = new File(filePath);
        if(!ServiceFilePath.exists()){
            ServiceFilePath.mkdirs();
        }

        //保存到服务器指定的文件夹
        file.transferTo(new File(filePath+newFilePath));

        return R.success(fileName);
    }


    @GetMapping("/download")
    public  void download(@RequestParam("name") String name , HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        //创建文件
        File file = new File(filePath + name);

        FileUtils.copyFile(file,response.getOutputStream());

    }
}
